package com.cc.eb.controller;

import com.cc.eb.model.EbUser;
import com.cc.eb.service.LoginService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 用一句话描述
 * @Auther: 新梦想*陈超
 * @Date: 2022/1/8 10:28
 */
@Controller
public class LoginController {
    @RequestMapping("/to_login")
    public String toLogin(){
        return  "login";//templates/login.html
    }

    //@RequestMapping("/register")
    //public String register(EbUser ebUser){}

    /**
     * 生成验证码的方法
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.out(request, response);
    }
    @Resource
    private LoginService  loginService;
    @RequestMapping("/login")
    public String login(EbUser ebUser, Model model, String verycode, HttpServletRequest request){
        model.addAttribute("error","");
        //TODO 1. 验证码校验
        if (!CaptchaUtil.ver(verycode, request)) {
            CaptchaUtil.clear(request);  // 清除session中的验证码
            model.addAttribute("error","验证码错误");
            return "forward:to_login";
        }
        //1.调用service完成登录
        EbUser lgnUser = loginService.login(ebUser);
        //2.绑定数据到model--session:  保存登录的用户信息
        request.getSession().setAttribute("lgnUser",lgnUser);
        //3.返回view--html
        return "redirect:/index/index";
    }
}
